# HLS色彩空间 与 颜色阈值

import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# 引入图片
image = mpimg.imread('test.jpg')

# 测试灰度图
thresh = (180, 255)
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
binary = np.zeros_like(gray)
binary[(gray > thresh[0]) & (gray <= thresh[1])] = 1

# 输出结果
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(22, 5))
f.tight_layout()
ax1.imshow(image)
ax1.set_title('Original Image', fontsize=20)
ax2.imshow(binary, cmap='gray')
ax2.set_title('Thresholded Gradient', fontsize=20)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
plt.show()

#使用单个RGB进行阈值处理
R = image[:,:,0]
G = image[:,:,1]
B = image[:,:,2]

# 输出结果
f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(22, 5))
f.tight_layout()
ax1.imshow(R, cmap='gray')
ax1.set_title('R', fontsize=20)
ax2.imshow(G, cmap='gray')
ax2.set_title('G', fontsize=20)
ax3.imshow(B, cmap='gray')
ax3.set_title('B', fontsize=20)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
plt.show()

# 不难看出 R通道 能很好地表现出车道线
thresh_R = (200, 255)
binary_R = np.zeros_like(R)
binary_R[(R > thresh_R[0]) & (R <= thresh_R[1])] = 1

# 可视化输出 R通道 与 R通道的二值图
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(22, 5))
f.tight_layout()
ax1.imshow(R, cmap='gray')
ax1.set_title('R Channel', fontsize=20)
ax2.imshow(binary_R, cmap='gray')
ax2.set_title('R Binary', fontsize=20)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
plt.show()

# 使用HLS色彩空间
hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)
H = hls[:,:,0]
L = hls[:,:,1]
S = hls[:,:,2]

# 输出 HLS 色彩空间得通道图
# 输出结果
f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(22, 5))
f.tight_layout()
ax1.imshow(H, cmap='gray')
ax1.set_title('H', fontsize=20)
ax2.imshow(L, cmap='gray')
ax2.set_title('L', fontsize=20)
ax3.imshow(S, cmap='gray')
ax3.set_title('S', fontsize=20)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
plt.show()

# S通道很好的识别了车道线 在S通道设置阈值
thresh_S = (90, 255)
binary_S = np.zeros_like(S)
binary_S[(S > thresh_S[0]) & (S <= thresh_S[1])] = 1

# 可视化
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(22, 5))
f.tight_layout()
ax1.imshow(S, cmap='gray')
ax1.set_title('S Channel', fontsize=20)
ax2.imshow(binary_S, cmap='gray')
ax2.set_title('S Binary', fontsize=20)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
plt.show()

# 在H通道中 车道线很暗 设置低阈值
thresh_H = (15, 100)
binary_H = np.zeros_like(H)
binary_H[(H > thresh_H[0]) & (H <= thresh_H[1])] = 1

# 可视化
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(22, 5))
f.tight_layout()
ax1.imshow(H, cmap='gray')
ax1.set_title('H Channel', fontsize=20)
ax2.imshow(binary_H, cmap='gray')
ax2.set_title('H_binary', fontsize=20)
plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
plt.show()